package com.example.springboot.controller.参数解析;


import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Controller
public class 域对象共享数据 {//spring mvc  有更详细的信息

    @GetMapping("/goto")
    public String goToPage(HttpServletRequest request){

        request.setAttribute("mag","成功了。。。。");//可写多个
        request.setAttribute("code",200);//可写多个

        return "forward:/success";//转发到/success请求
    }

    @GetMapping("/params")
    public String testParam(Map<String,Object> map,
                            Model model,
                            HttpServletRequest request,
                            HttpServletResponse response){
        /**
         * Map、Model、ModelMap
         * （map、model、ModelMap里面的数据会被放在request的请求域
         * request.setAttribute）
         *
         * Map、Model、ModelMap（这俩个相当于同一个对象）类型的参数会返回 mavContainer.getModel（）；
         * ---> BindingAwareModelMap 是Model 也是Map
         * mavContainer.getModel(); 获取到值的
         *
         */
        map.put("map","map");
        model.addAttribute("model","model");


        request.setAttribute("request","request");//可写多个
        Cookie cookie = new Cookie("c1","v1");//
        cookie.setDomain("localhost");
        response.addCookie(cookie);

//        最后都会遍历  会被放在 request的请求域中
        return "forward:/success";//转发到/success请求
    }

    @ResponseBody
    @GetMapping("/success")
    public Map success(@RequestAttribute(value = "mag",required = false) String mag,//获取指定的
                       //可以获取转发前HttpServletRequest里的数据 （它传进来的）
                       @RequestAttribute(value = "code",required = false) String code,
                       HttpServletRequest request){//获取全部的HttpServletRequest
//        @RequestAttribute(value = "mag",required = false(表示这个东西不是必须的))  默认true
        Object mag1=request.getAttribute("mag");

        Map<String,Object> map=new HashMap<>();
        map.put("HttpServletRequest",mag1);
        map.put("RequestAttribute_mag",mag);
        map.put("RequestAttribute_code",code);
        map.put("request_map",request.getAttribute("map"));
        map.put("request_model",request.getAttribute("model"));
        map.put("request_request",request.getAttribute("request"));
//        map.put("request_",request.getAttribute("map"));


        return map;
    }
}


